<template>
  <view class="content">
    <view class="mask" v-if="!deviceID">
      <view class="mask-content">
        <view class="mask-title">需要绑定设备ID</view>
        <input
          class="mask-input"
          type="text"
          v-model="tempDeviceId"
          placeholder="请输入设备ID"
        />
        <view class="btn-box">
          <button class="mask-button" @click="tempDeviceId = ''">清空</button>
          <button type="primary" class="mask-button" @click="confirmDeviceId">
            提交
          </button>
        </view>
      </view>
    </view>
    <!-- <cover-view @click="download" class="cover-view">下载</cover-view> -->
    <view class="tips-box" v-else-if="!webViewUrl">
      找不到广告内容，广告成功下发后会在{{ uploadTimeMinute }}分钟内更新！！
      <button v-if="deviceID" @click="resetDeviceId">重置设备ID</button>
    </view>
    <view class="web-view-content" v-else>
      <cover-view class="setting-mask" @click="settingStatus = !settingStatus">
        <cover-view class="setting" v-if="settingStatus">
          <cover-view class="btn" @click="resetDeviceId">重置设备ID</cover-view>
        </cover-view>
      </cover-view>
      <web-view class="web" :src="webViewUrl"></web-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      requestUrl: "http://test.el.tldt.net/prod-api",
      hostUrl: "https://elevator-file.obs.cn-south-1.myhuaweicloud.com",
      downloadurl: "",
      webViewUrl: "",
      deviceID: "",
      tempDeviceId: "",
      fileIndex: 0, //文件的下标，多个广告会叠加
      timeoutFu: null,
      uploadTimeMinute: 1, //多少分钟更新
      settingStatus: false, //打开设置
    };
  },
  onLoad() {
    // uni.setStorageSync("deviceID", "");
    // uni.setStorageSync("downloadurl", "");
    this.init();
  },
  watch: {
    settingStatus(val) {
      if (val) {
        setTimeout(() => {
          this.settingStatus = false;
        }, 5000);
      }
    },
  },
  onShow() {
    this.uploadTimeout();
  },
  methods: {
    setWebviewTopbar() {
      uni.getSystemInfo({
        // 获取当前设备的具体信息
        success: (sysinfo) => {
          let statusbar = sysinfo.statusBarHeight; // 动态状态栏高度
          let height = sysinfo.windowHeight; // 动态高度变量
          setTimeout(() => {
            let currentWebview = this.$scope.$getAppWebview(); // 获取当前web-view
            const wv = currentWebview.children()[0]; // 获取web-view的子节点（即需要设置样式的元素）

            console.log("currentWebview- wv", wv);
            if (wv) {
              wv.setStyle({
                // 设置web-view距离顶部的距离以及自己的高度,单位为px
                top: statusbar, // 距离顶部的高度,应该是你页面的头部
                height: height, // webview的高度
              });
            }
          }, 1000); // 如页面初始化调用需要写延迟
        },
      });
    },
    init() {
      const deviceID = uni.getStorageSync("deviceID");
      console.log(deviceID, "deviceID");
      if (deviceID) {
        this.webViewUrl = "";
        this.deviceID = deviceID;
        const downloadurl = uni.getStorageSync("downloadurl");
        if (downloadurl) {
          this.downloadurl = downloadurl;
          this.download();
        }
      } else {
      }
    },
    uploadTimeout() {
      console.log("开始更新");
      uni.request({
        url:
          this.requestUrl +
          "/elevator/openapi/heartbeat/adDev?baseAdDevId=" +
          this.deviceID,
        success: (res) => {
          console.log("获取到数据", res);
          const data = res.data.data;
          if (data && data !== this.downloadurl) {
            this.fileIndex += 1;
            this.downloadurl = data;
            console.log("request-data", data);
            this.download();
            uni.setStorageSync("downloadurl", data);
            console.log(
              "uni.getStorageSync",
              uni.getStorageSync("downloadurl")
            );
          }
        },
      });
      this.clearTime();
      this.timeoutFu = setTimeout(() => {
        this.uploadTimeout();
        // }, 10 * 1000);
      }, this.uploadTimeMinute * 60 * 1000);
    },
    clearTime() {
      this.timeoutFu && clearTimeout(this.timeoutFu);
    },
    download() {
      console.log("download-url", this.hostUrl + this.downloadurl);
      uni
        .downloadFile({
          url: this.hostUrl + this.downloadurl,
          complete: (com) => {
            if (com.statusCode == 200) {
              // this.tempFilePath = com.tempFilePath
              uni.saveFile({
                tempFilePath: com.tempFilePath,
                success: (res) => {
                  // 文件的保存路径
                  console.log(res.savedFilePath); //_doc/uniapp_save/17110001966500.zip
                  console.log(plus.io.PRIVATE_DOC, "plus.io");
                  this.onZipFile(res.savedFilePath);
                },
              });
            } else {
              console.log("下载失败，请重试！");
            }
          },
        })
        .onProgressUpdate((res) => {
          this.percentage = res.progress;
        });
    },
    // 解压zip文件
    onZipFile(zipfileUrl) {
      const zipfile = plus.io.convertLocalFileSystemURL(zipfileUrl);
      console.log("zipfile绝对路径: " + zipfile);
      const date = new Date();
      const y = date.getFullYear();
      const m = date.getMonth();
      const d = date.getDay();
      let t = `${y}-${m}-${d}-${this.fileIndex}/`;
      console.log("日期", t);
      let targetPath = "_doc/hybrid/html/zip/" + t;
      targetPath = plus.io.convertLocalFileSystemURL(targetPath);
      console.log("targetPath绝对路径: " + targetPath);

      plus.zip.decompress(
        zipfile,
        targetPath,
        (res) => {
          console.log("解压缩成功!" + res);
          // uni.showToast({ title: '解压缩成功!', icon: 'none' });
          // uni.navigateTo({
          // 		url: '../web-view.d?cid=webid&name=webname'
          // });
          this.webViewUrl = targetPath + "index.html";
          this.setWebviewTopbar();
          // this.getFileUrl(targetPath)
        },
        function (error) {
          console.log("解压缩失败: " + JSON.stringify(error));
          uni.showToast({ title: "解压缩失败!", icon: "none" });
        }
      );
    },
    // 获取文档目录
    getFileUrl(url) {
      plus.io.resolveLocalFileSystemURL(
        url,
        (entry) => {
          console.log(entry, "resolveLocalFileSystemURL-s");
          const directoryReader = entry.createReader(); //创建目录读取对象
          directoryReader.readEntries(
            (entries) => {
              //返回的是指定文件夹下的文件列表和 uni.getSavedFileList(OBJECT)效果一样
              for (let i = 0; i < entries.length; i++) {
                // console.log(
                // entries[i].fullPath, // 文件路径
                // entries[i].fileSystem,
                // Object.keys(entries[i])
                // );
                console.log(entries[i].name); //文件名称
              }
              console.log(entries[0].name);
            },
            (err) => {
              console.log("访问目录失败: ", err);
            }
          );
        },
        (error) => {
          console.log(error, "resolveLocalFileSystemURL-error");
        }
      );
    },
    // 拿到 _doc 所在的完整路径
    requestFileSystem() {
      plus.io.requestFileSystem(
        plus.io.PRIVATE_DOC,
        (fs) => {
          // console.log(json);
          // console.log(JSON.stringify(fs.root));
          console.log(fs.root.fullPath, "fullPath"); ///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/
        },
        function (e) {
          console.log("Request file system failed: " + e.message);
        }
      );
    },
    // 提交设备ID
    confirmDeviceId() {
      // if (!this.tempDeviceId) return;
      uni.setStorageSync("deviceID", this.tempDeviceId);
      this.init();
    },
    resetDeviceId() {
      const id = this.deviceID;
      if (id) {
        this.tempDeviceId = id;
      }
      this.deviceID = "";
      this.settingStatus = false;
    },
  },
};
</script>

<style lang="scss">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0rpx;
  margin: 0;
  position: relative;
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
}
.cover-view {
  padding: 20px;
  background: red;
  color: #fff;
  z-index: 999;
}
.mask {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  position: absolute;
  left: 0;
  top: 0;
  z-index: 99;
  display: flex;
  align-items: center;
  justify-content: center;
  .mask-content {
    background-color: #fff;
    width: 80%;
    padding: 30rpx;
    .mask-title {
      text-align: center;
      padding: 50rpx;
      font-weight: bold;
      font-size: 29rpx;
    }
    .mask-input {
      border-radius: 7rpx;
      border: 1rpx solid #888;
      height: 80rpx;
      line-height: 80rpx;
      padding: 5rpx 20rpx;
    }
    .btn-box {
      margin-top: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      .mask-button {
      }
    }
  }
}
.tips-box {
  font-size: 30rpx;
  line-height: 1.6;
  padding: 50rpx 20rpx;
}
.web-view-content {
  width: 100%;
  height: 100%;
  position: relative;
  .web {
    height: 100%;
    width: 100%;
    padding: 0;
    margin: 0;
    position: absolute;
    z-index: 9;
  }
  .setting-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
    background: transparent;
    .setting {
      position: absolute;
      top: 100rpx;
      left: 0;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .btn {
        padding: 0 20rpx;
        height: 50rpx;
        line-height: 50rpx;
        text-align: center;
        border-radius: 10rpx;
        background: rgba(0, 0, 0, 0.6);
        color: #fff;
        &:active {
          background: rgba(0, 0, 0, 0.4);
        }
      }
    }
  }
}
</style>
